<template>
  <div class="app-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>我参与的项目</h2>
      <div class="header-actions">
        <div class="header-stats">
          <el-tag type="info">未开始 {{ getStatusCount(0) }}</el-tag>
          <el-tag type="primary">进行中 {{ getStatusCount(1) }}</el-tag>
          <el-tag type="success">已完成 {{ getStatusCount(2) }}</el-tag>
        </div>
        <el-button type="primary" icon="el-icon-message" @click="handleViewInvitations">
          查看邀请
        </el-button>
      </div>
    </div>


    <!-- 搜索筛选 -->
    <el-card class="search-card" shadow="never">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input v-model="searchForm.title" placeholder="搜索项目名称" prefix-icon="el-icon-search" clearable
            @keyup.enter.native="handleSearch" />
        </el-col>
        <el-col :span="6">
          <el-select v-model="searchForm.status" placeholder="项目状态" clearable style="width: 100%">
            <el-option label="未开始" :value="0" />
            <el-option label="进行中" :value="1" />
            <el-option label="已完成" :value="2" />
          </el-select>
        </el-col>
        <el-col :span="10">
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-col>
      </el-row>
    </el-card>

    <!-- 项目表格 -->
    <el-table v-loading="loading" :data="projectList" element-loading-text="加载中..." border fit highlight-current-row
      style="width: 100%">
      <el-table-column label="项目名称" min-width="250" align="left">
        <template slot-scope="{row}">
          <div class="project-name-cell">
            <div class="project-title" @click="handleDetail(row)">{{ row.title }}</div>
            <div class="project-desc">{{ row.description }}</div>
          </div>
        </template>
      </el-table-column>

      <el-table-column label="指导教师" width="120" align="center">
        <template slot-scope="{row}">
          <span>{{ row.teacherName }}</span>
        </template>
      </el-table-column>

      <el-table-column label="项目时间" width="200" align="center">
        <template slot-scope="{row}">
          <div>{{ row.startDate }}</div>
          <div style="color: #909399; font-size: 12px;">至 {{ row.endDate }}</div>
        </template>
      </el-table-column>

      <el-table-column label="加入时间" width="120" align="center">
        <template slot-scope="{row}">
          <span>{{ row.joinTime }}</span>
        </template>
      </el-table-column>

      <el-table-column label="节点数量" width="100" align="center">
        <template slot-scope="{row}">
          <el-tag size="small">{{ row.projectMilestoneNum }}个</el-tag>
        </template>
      </el-table-column>

      <el-table-column label="完成进度" width="150" align="center">
        <template slot-scope="{row}">
          <el-progress :percentage="getProgress(row)" :status="getProgressStatus(row)" :stroke-width="6"
            :show-text="false" />
          <div style="font-size: 12px; color: #909399; margin-top: 4px;">
            {{ getProgress(row) }}%
          </div>
        </template>
      </el-table-column>

      <el-table-column label="状态" width="100" align="center">
        <template slot-scope="{row}">
          <el-tag :type="getStatusType(row.status)">
            {{ getStatusText(row.status) }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column label="操作" width="100" align="center" fixed="right">
        <template slot-scope="{row}">
          <el-button type="primary" size="mini" @click="handleDetail(row)">
            查看详情
          </el-button>
        </template>
      </el-table-column>
    </el-table>


    <!-- 分页 -->
    <div class="pagination-wrapper" v-if="total > 0">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page="pagination.pageNo" :page-sizes="[10, 20, 50]" :page-size="pagination.pageSize"
        layout="total, sizes, prev, pager, next, jumper" :total="total" />
    </div>
  </div>
</template>

<script>
import { parseTime } from '@/utils'
import { getStudentProjectList } from '@/api/research'

export default {
  name: 'StudentProjects',
  filters: {
    parseTime
  },
  data() {
    return {
      loading: false,
      searchForm: {
        title: '',
        status: null
      },
      pagination: {
        pageNo: 1,
        pageSize: 10
      },
      total: 0,
      projectList: [],
      milestoneData: {} // 存储每个项目的节点数据
    }
  },
  created() {
    this.loadProjects()
  },
  methods: {
    // 加载项目列表
    loadProjects() {
      this.loading = true

      getStudentProjectList({
        ...this.searchForm,
        ...this.pagination
      }).then(response => {
        this.projectList = response.data.records
        this.total = response.data.total
        this.loading = false
      }).catch(() => {
        // 模拟数据
        setTimeout(() => {
          this.projectList = [
            {
              id: 1,
              title: '深度学习图像识别研究',
              description: '研究深度学习在图像识别领域的应用，包括CNN、目标检测等技术',
              teacherId: 2,
              teacherName: '张教授',
              startDate: '2025-09-01',
              endDate: '2026-06-30',
              status: 1,
              joinTime: '2025-09-05 14:00:00'
            },
            {
              id: 3,
              title: '区块链供应链应用',
              description: '研究区块链技术在供应链管理中的实际应用',
              teacherId: 2,
              teacherName: '王教授',
              startDate: '2025-08-01',
              endDate: '2025-12-31',
              status: 2,
              joinTime: '2025-08-05 16:00:00'
            }
          ]

          // 模拟节点数据
          this.milestoneData = {
            1: { total: 4, completed: 1 },
            3: { total: 2, completed: 2 }
          }

          this.total = this.projectList.length
          this.loading = false
        }, 1000)
      })
    },


    // 搜索
    handleSearch() {
      this.pagination.pageNo = 1
      this.loadProjects()
    },

    // 重置搜索
    handleReset() {
      this.searchForm = {
        title: '',
        status: null
      }
      this.handleSearch()
    },

    // 分页
    handleSizeChange(size) {
      this.pagination.pageSize = size
      this.loadProjects()
    },

    handleCurrentChange(page) {
      this.pagination.pageNo = page
      this.loadProjects()
    },

    // 操作方法
    handleDetail(project) {
      this.$router.push(`/research/student-detail/${project.id}`)
    },

    handleViewProject(projectId) {
      this.$router.push(`/research/student-detail/${projectId}`)
    },

    handleViewInvitations() {
      this.$router.push('/research/invitations')
    },

    // 工具方法
    getStatusType(status) {
      const types = { 0: 'info', 1: 'primary', 2: 'success' }
      return types[status] || 'info'
    },

    getStatusText(status) {
      const texts = { 0: '未开始', 1: '进行中', 2: '已完成' }
      return texts[status] || '未知'
    },

    getStatusCount(status) {
      return this.projectList.filter(p => p.status === status).length
    },

    getMilestoneCount(project) {
      const data = this.milestoneData[project.id]
      return data ? data.total : 0
    },

    getProgress(project) {
      const status = parseInt(project.status)

      // 如果项目已完成，直接返回100%
      if (status === 2) return 100

      // 如果项目未开始，返回0%
      if (status === 0) return 0

      // 根据时间计算进度
      try {
        const startDate = new Date(project.startDate)
        const endDate = new Date(project.endDate)
        const currentDate = new Date()

        // 检查日期有效性
        if (isNaN(startDate.getTime()) || isNaN(endDate.getTime())) {
          return 0
        }

        // 如果当前时间在开始时间之前，返回0%
        if (currentDate < startDate) {
          return 0
        }

        // 如果当前时间在结束时间之后，根据状态返回进度
        if (currentDate >= endDate) {
          return status === 2 ? 100 : 95 // 已完成100%，否则95%（表示已到期但未完成）
        }

        // 计算时间进度
        const totalDuration = endDate.getTime() - startDate.getTime()
        const elapsedDuration = currentDate.getTime() - startDate.getTime()

        if (totalDuration <= 0) return 0

        const timeProgress = Math.round((elapsedDuration / totalDuration) * 100)

        // 确保进度在0-100之间
        return Math.max(0, Math.min(100, timeProgress))
      } catch (error) {
        console.error('计算项目进度失败:', error)
        // 如果时间计算失败，根据状态返回基础进度
        if (status === 0) return 0
        if (status === 1) return 50
        if (status === 2) return 100
        return 0
      }
    },

    getProgressStatus(project) {
      const status = parseInt(project.status)
      const progress = this.getProgress(project)

      // 已完成项目显示成功状态
      if (status === 2) return 'success'

      // 检查是否已过期
      try {
        const currentDate = new Date()
        const endDate = new Date(project.endDate)

        // 如果项目已过期但未完成，显示异常状态
        if (currentDate >= endDate && status !== 2) {
          return 'exception'
        }
      } catch (error) {
        console.error('检查项目过期状态失败:', error)
      }

      // 根据时间进度显示状态
      if (progress >= 80) return 'success'   // 进度良好
      if (progress >= 50) return ''          // 正常进度
      if (progress >= 20) return ''          // 正常进度
      return 'exception'                     // 进度较慢
    },

  }
}
</script>

<style scoped>
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  color: #303133;
  font-size: 24px;
  font-weight: 600;
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 16px;
}

.header-stats {
  display: flex;
  gap: 12px;
}


.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}


.search-card {
  margin-bottom: 20px;
  border: 1px solid #EBEEF5;
}

.project-name-cell {
  text-align: left;
}

.project-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  cursor: pointer;
  margin-bottom: 4px;
  line-height: 1.4;
}

.project-title:hover {
  color: #409EFF;
}

.project-desc {
  color: #909399;
  font-size: 13px;
  line-height: 1.4;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  margin: 0;
}


.pagination-wrapper {
  display: flex;
  justify-content: center;
  margin-top: 30px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 16px;
  }

}
</style>